<template>
  <el-dialog
    :title="textMap[dialogStatus]"
    width="80%"
    :visible.sync="dialogFormVisible"
    :close-on-click-modal="false"
    top="24px"
  >
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="form"
      label-position="right"
      label-width="100px"
      v-loading="confirmLoading"
    >
      <el-form-item label="考试名称" prop="name">
        <el-select
          v-model="form.name"
          style="width: 100%"
          placeholder="请选择考试名称"
          :disabled ="dialogStatus =='update'"
          @change="changeName"
        >
          <el-option
            label="贵阳市建筑施工特种作业人员理论考试试卷"
            value="贵阳市建筑施工特种作业人员理论考试试卷"
          ></el-option>
          <el-option
            label="贵阳市建筑施工企业“安管人员”安全生产知识考试试卷"
            value="贵阳市建筑施工企业“安管人员”安全生产知识考试试卷"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="考试期数" prop="period">
        <el-input
          placeholder="请输入"
          type="text"
          v-model="form.period"
          style="width: 100%;"
        >
        </el-input>
      </el-form-item> -->

      <el-form-item label="考试期数" required style="margin-bottom: 0">
        <el-col :span="11">
          <el-form-item prop="year">
            <el-input
              placeholder="年份"
              type="number"
              v-model="form.year"
              :min="1"
            >
              <span slot="append">年</span>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-form-item prop="phase">
            <el-input
              placeholder="期数"
              type="number"
              v-model="form.phase"
              :min="1"
            >
              <span slot="prepend">第</span>
              <span slot="append">期</span>
            </el-input>
          </el-form-item>
        </el-col>
      </el-form-item>

      <el-form-item label="考试时间" prop="testDate">
        <el-date-picker
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="日期"
          v-model="form.testDate"
          :picker-options="pickerOptionsStart"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="随机抽题" prop="random">
        <el-radio-group v-model="form.random">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>


      <el-form-item prop="templateIds" label="模板名称">
        <el-select
          v-model="form.templateIds"
          style="width: 100%"
          placeholder="请选择模板"
          @change="changeTemplate"
          :disabled ="true"
        >
          <el-option
            v-for="item in templateList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="内容设置" required style="margin-bottom: 0">
        <el-col :span="5">
          <el-form-item prop="templateIds">
            <el-select
              v-model="form.templateIds"
              style="width: 100%"
              placeholder="请选择模板"
              @change="changeTemplate"
              :disabled ="true"
            >
              <el-option
                v-for="item in templateList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="1">-</el-col>
        <el-col :span="9">
          <el-form-item prop="type">
            <el-select
              :multiple="dialogStatus !='update'"
              v-model="form.type"
              style="width: 100%"
              placeholder="请选择类别"
            >
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="1">-</el-col>
        <el-col :span="7">
          <el-form-item prop="qusLibIds">
            <el-select
              multiple
              v-model="form.qusLibIds"
              style="width: 100%"
              placeholder="请选择题库"
            >
              <el-option
                v-for="item in qusLibList"
                :key="item.id"
                :label="item.libName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item> -->

      <el-divider>规则设置</el-divider>
      <!-- <el-row>
        <el-col :span="12" v-for="(item, index) in form.examQusList">
          <el-form-item
            :key="item.qusType"
            :label="item.qusTypeDesc"
            required
            label-width="80"
            style="margin-bottom:0"
          >
            <el-col :span="9">
              <el-form-item
                :prop="'examQusList.' + index + '.qusNum'"
                :rules="{
                  required: true,
                  message: '单选题目数量不能为空',
                  trigger: 'blur'
                }"
              >
                <el-input placeholder="数量" type="number" v-model="item.qusNum">
                  <span slot="prepend">数量</span>
                  <span slot="append">个</span>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col class="line" :span="2">-</el-col>
            <el-col :span="10">
              <el-form-item
                :prop="'examQusList.' + index + '.qusScore'"
                :rules="{
                  required: true,
                  message: '单选单个题目分值不能为空',
                  trigger: 'blur'
                }"
              >
                <el-input
                  placeholder="单个分值"
                  type="number"
                  v-model="item.qusScore"
                >
                  <span slot="prepend">单个分值</span>
                  <span slot="append">分</span>
                </el-input>
              </el-form-item>
            </el-col>
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-form-item
        v-for="(item, index) in form.examQusList"
        :key="item.qusType"
        :label="item.qusTypeDesc"
        required
        style="margin-bottom:0"
      >
        <el-col :span="11">
          <el-form-item
            :prop="'examQusList.' + index + '.qusNum'"
            :rules="{
              required: true,
              message: '单选题目数量不能为空',
              trigger: 'blur'
            }"
          >
            <el-input placeholder="数量" type="number" v-model="item.qusNum" :disabled="dialogStatus =='update'">
              <span slot="prepend">数量</span>
              <span slot="append">个</span>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-form-item
            :prop="'examQusList.' + index + '.qusScore'"
            :rules="{
              required: true,
              message: '单选单个题目分值不能为空',
              trigger: 'blur'
            }"
          >
            <el-input
              placeholder="单个分值"
              type="number"
              v-model="item.qusScore"
              :disabled="dialogStatus =='update'"
            >
              <span slot="prepend">单个分值</span>
              <span slot="append">分</span>
            </el-input>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="满分" prop="totalScore">
            <el-input
              readonly
              placeholder="满分"
              type="number"
              v-model="form.totalScore"
            >
              <span slot="append">分</span>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-form-item label="组卷方式" prop="methods">
        <el-radio-group v-model="form.methods">
            <el-radio :label="1">对应抽题</el-radio>
            <el-radio :label="0">组合抽题</el-radio>
        </el-radio-group>
      </el-form-item> -->

      <el-divider>类别、题库、比例</el-divider>
      <el-card shadow="never" class="custom-exam-card" v-for="(item, index) in form.papers" :key="index">
        <div slot="header" class="clearfix">
          <el-row type="flex" justify="end" v-if="dialogStatus !='update'">
            <el-button
              @click.prevent="removePaper(item)"
              type="danger"
              icon="el-icon-delete"
              circle
              title="删除"
              plain
              v-if="form.papers.length > 1"
             ></el-button>
            <el-button
            type="primary"
            icon="el-icon-plus"
            circle
            title="添加"
            plain
            @click="addPaper"
            v-if="index === form.papers.length-1"
            ></el-button>
          </el-row>
        </div>
        <el-form-item
          label="类别及题库"
          style="margin-bottom:0"
          required
        >
          <el-col :span="9">
            <el-form-item
              :prop="'papers.' + index + '.type'"
              :rules="{
                required: true,
                message: '请选择',
                trigger: 'change'
              }"
            >
             <el-select
               v-model="item.type"
               style="width: 100%"
               placeholder="请选择类别"
             >
               <el-option
                 v-for="item in typeList"
                 :key="item.id"
                 :label="item.name"
                 :value="item.id"
               ></el-option>
             </el-select>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="1">-</el-col>
          <el-col :span="14">
            <el-form-item
              :prop="'papers.' + index + '.qusLibId'"
              :rules="{
                required: true,
                message: '请选择',
                trigger: 'change'
              }"
            >
              <el-select
                multiple
                v-model="item.qusLibId"
                style="width: 100%"
                placeholder="请选择题库"
              >
                <el-option
                  v-for="item in qusLibList"
                  :key="item.id"
                  :label="item.libName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-row :gutter="24">
          <el-col :sm="12" :md="form.templateIds =='TZ'?8:6" v-for="(ratio, order) in item.examRatioList" :key="order">
            <el-form-item
              :key="order"
              :label="ratio.qusPropTypeDesc"
              :prop="'papers.' + index + '.examRatioList.' + order + '.qusRadio'"
              label-width="135px"
              :rules="{
                required: true,
                message: '请选择',
                trigger: 'change'
              }"
              style="margin-bottom: 0;"
            >
             <el-input
               placeholder="占比"
               type="number"
               v-model="ratio.qusRadio"
               @change="calcRatio(item, index, ratio, order)"
             >
               <span slot="append">%</span>
             </el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-card>





      <!-- <el-form-item label="考试时限" prop="num">
        <el-input
          readonly
          placeholder="时限"
          type="number"
          style="width: 20%;"
          v-model="form.num"
        >
          <span slot="append">分钟</span>
        </el-input>
      </el-form-item> -->
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">
        取消
      </el-button>
      <el-button :loading="confirmLoading" type="primary" @click="submitForm">
        确认
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import formMixin from "@/mixins/form";
import request from "@/utils/request";
export default {
  name: "Dialog",
  mixins: [formMixin],
  components: {},
  data() {
    return {
      textMap: {
        update: "修改试卷",
        create: "生成试卷"
      },
      rules: {
        name: [
          {
            required: true,
            message: "请选择名称",
            trigger: "blur"
          }
        ],
        templateIds: [
          {
            required: true,
            message: "请选择",
            trigger: "change"
          }
        ],
        year: [
          {
            required: true,
            message: "请输入",
            trigger: "blur"
          }
        ],
        phase: [
          {
            required: true,
            message: "请输入",
            trigger: "blur"
          }
        ],
        testDate: [
          {
            required: true,
            message: "请选择",
            trigger: "change"
          }
        ],
        random: [
          {
            required: true,
            message: "请输入",
            trigger: "blur"
          }
        ]
      },
      qusLibList: [],
      templateList: [
        {
          id:'AG',
          name: '安管人员模板'
        },
        {
          id:'TZ',
          name: '特种作业人员模板'
        }
      ],
      types: {
        'AG': [
          {
            id:'企业主要负责人',
            name: 'A类：企业主要负责人'
          },
          {
            id:'项目负责人',
            name: 'B类：项目负责人'
          },
          {
            id:'机械类专职安全生产管理人员',
            name: 'C1类：机械类专职安全生产管理人员'
          },
          {
            id:'土建类专职安全生产管理人员',
            name: 'C2类：土建类专职安全生产管理人员'
          },
          {
            id:'综合类专职安全生产管理人员',
            name: 'C3类：综合类专职安全生产管理人员'
          }
        ],
        'TZ': [
          {
            id:'建筑电工',
            name: '建筑电工'
          },
          {
            id:'建筑架子工',
            name: '建筑架子工'
          },
          {
            id:'建筑起重司索信号工',
            name: '建筑起重司索信号工'
          },
          {
            id:'建筑起重塔式起重机司机',
            name: '建筑起重塔式起重机司机'
          },
          {
            id:'建筑起重施工升降机司机',
            name: '建筑起重施工升降机司机'
          },
          {
            id:'建筑起重物料提升机司机',
            name: '建筑起重物料提升机司机'
          },
          {
            id:'建筑起重机械安装拆卸工',
            name: '建筑起重机械安装拆卸工'
          },
          {
            id:'建筑焊工',
            name: '建筑焊工'
          },
          {
            id:'建筑土石方机械操作工',
            name: '建筑土石方机械操作工'
          },
          {
            id:'高处作业吊篮安装拆卸工',
            name: '高处作业吊篮安装拆卸工'
          },
          {
            id:'建筑中小型机械操作工',
            name: '建筑中小型机械操作工'
          }
        ]
      },
      typeList: [],
      Urls: {
        qusLibListUrl: "/api/question/lib/list",
        addUrl: "/api/exam/paper/insert",
        editUrl: "/api/exam/paper/record/update/",
        getByIdUrl: "/api/exam/paper/record/get/",
        dictTypeUrl: '/api/dict/typeList',
      },
      qus_type: [],
      examToQusType: {
        AG: 'safty_paper_qus_type',
        TZ: 'special_qus_type',
      },
    };
  },
  computed: {},
  watch: {
    "form.examQusList": {
      handler(newVal, oldVal) {
        if (newVal.length > 0) {
          let total = 0;
          this.form.examQusList.map(item => {
            total = total + (item.qusNum || 0) * (item.qusScore || 0);
          });
          this.form.totalScore = total;
        }
      },
      deep: true
    }
  },
  methods: {
    beforeOpen(row) {
      if (row && row.name) {
        this.changeName(row.name)
      } else{
        // 切换考试内容
        this.getDictData(this.examToQusType['AG'],'qus_type')
      }
      this.getQusLibList();
    },
    resetForm() {
      this.form ={year: Number(new Date().getFullYear()),phase:1,
        papers: [
          {
            type: '',
            qusLibId: [],
            examRatioList: []
          },
        ],
        examQusList: [
          { qusType: "choice", qusTypeDesc: "单选", qusNum: 90, qusScore: 1 },
          { qusType: "judge", qusTypeDesc: "判断", qusNum: 10, qusScore: 1 }
        ]
      }
    },
    fillForm(data) {
      this.form = Object.assign({}, data, {
        papers: [
          {
            qusLibId: data.qusLibIds.split(","),
            type: data.type,
            examRatioList: data.examRatioList
          }
        ],
        examQusList: [
          { qusType: "choice", qusTypeDesc: "单选", qusNum: data.choiceNum, qusScore: data.choiceScore },
          { qusType: "judge", qusTypeDesc: "判断", qusNum: data.judgeNum, qusScore: data.judgeScore }
        ],
      })
      // 有期数
      if(data.period) {
        // 年及期数
        const times = data.period.split(/[年第期]/).filter(item => item)
        // 年
        this.$set(this.form,'year', times[0])
        // 期数
        this.$set(this.form,'phase', times[1])
      }
      // 名称
      this.form.name = data.paperName
      // ，模板
      this.form.templateIds = data.template
      if(data.template) {
        this.typeList = [...this.types[data.template]]
      }
    },
    formatData(data) {
      let form = Object.assign({}, data);
      form.examQusList.forEach(item => {
        item.randomType = form.random
      })
      let ids = [],arr = this.qusLibList,names = [],papers = form.papers;
      if (papers && papers.length > 0) {
        papers.forEach(item => {
          names = []
          if (item.qusLibId && item.qusLibId.length > 0) {
            for (let i = 0; i < arr.length; i++) {
              for (let j = 0; j < item.qusLibId.length; j++) {
                if (item.qusLibId[j] == arr[i].id) {
                  names.push(arr[i].libName);
                }
              }
            }
          }
          item.qusLibIds = item.qusLibId.join()
          item.qusLibNames = names.join()
          item.template = form.templateIds
        })
        form.papers = papers
      }
      if (this.dialogStatus != 'create') {
        form.type = form.papers[0].type
        form.qusLibIds = form.papers[0].qusLibIds
        form.qusLibNames = form.papers[0].qusLibNames
        form.examRatioList = form.papers[0].examRatioList
      }

      if(form.year) {
        form.period = form.year + '年'
      }
      if(form.phase) {
        form.period += '第' + form.phase + '期'
      }
      form.paperName = form.name
      return form;
    },
    changeName(val) {
      if (val === '贵阳市建筑施工特种作业人员理论考试试卷') {
        this.$set(this.form, 'templateIds','TZ')
        // 切换考试内容
        this.getDictData(this.examToQusType['TZ'],'qus_type')
      } else {
        this.$set(this.form, 'templateIds','AG')
        // 切换考试内容
        this.getDictData(this.examToQusType['AG'],'qus_type')
      }
      if(val) {
        this.typeList = [...this.types[this.form.templateIds]]
      }
      this.$set(this.form, 'type',[])
    },
    changeTemplate(val) {
      if(val) {
        this.typeList = [...this.types[val]]
      }
      this.form.type = undefined
    },
    /**
     * 添加试卷
     */
    addPaper() {
      let papers = this.form.papers
      let examRatioList = []
      for (var i = 0; i < this.qus_type.length; i++) {
        examRatioList.push({
          qusPropType: this.qus_type[i].key,
          qusPropTypeDesc: this.qus_type[i].value,
          qusRadio: 10,
        })
      }
      papers.push({
        type: '',
        qusLibIds: [],
        examRatioList: examRatioList
      })
      this.$set(this.form,'papers', papers)
    },
    /**
     * 删除试卷
     * @param {Object} item
     */
    removePaper(item) {
      const index = this.form.papers.indexOf(item)
      if (index !== -1) {
        this.form.papers.splice(index, 1)
      }
    },
    calcRatio(record, index, ratio, order) {
      let surplusRatio = 100 - ratio.qusRadio

      // record.examRatioList
    },
    // 时间格式
    endTimeChange(date) {
      this.form.endTime = `${date} 23:59:59`;
    },
    // 获取题库
    getQusLibList() {
      const that = this
      request({
        url: that.Urls.qusLibListUrl,
        method: "get"
      })
        .then(res => {
          console.log("form list", res);
          if (res.code == 0) {
            that.qusLibList = res.data.records || [];
          } else {
            that.$notify({
              title: "提示",
              message: res.msg,
              type: "error",
              duration: 2000
            });
          }
        })
        .catch(err => {
          that.dialogFormVisible = false;
        });
    },
    getqusLibName(val) {
      let ids = val,
        arr = this.qusLibList,
        names = [];
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < ids.length; j++) {
          if (ids[j] == arr[i].id) {
            names.push(arr[i].libName);
          }
        }
      }

      /* let obj = this.qusLibList.find(item => {
        return item.id === val;
      }); */
      console.log("题库", names);
      this.form.qusLibNames = names.join(",");
    },
    submitForm() {
      let that = this
      let url = {
        update: that.Urls.editUrl + that.form.id,
        create: that.Urls.addUrl
      }
      console.log('form', that.form)
      that.$refs["dataForm"].validate(valid => {
        if (valid) {
          let formData = that.formatData(that.form)
          this.confirmLoading = true
          request({
            url: url[that.dialogStatus],
            method: 'post',
            data: formData
          }).then((res) => {
            console.log('res form', res)
            this.confirmLoading = false
            if (res.code == 0) {
              that.$notify({
                title: '提示',
                message: that.tipMap[that.dialogStatus],
                type: 'success',
                duration: 2000
              })
              that.dialogFormVisible = false
              that.$parent.afterSubmit()
            } else {
              that.$notify({
                title: '提示',
                message: res.msg,
                type: 'error',
                duration: 2000
              })
            }
          }).catch((err) => {
            this.confirmLoading = false
          })
        }
      });
    },
    // 获取一级字典数据
    getDictData(type, data) {
      request({
        url: this.Urls.dictTypeUrl,
        method: 'get',
        params: {
          type: type
        }
      }).then(res => {
        if (res.code == 0) {
          this[data] = res.data.records
          this.afterGetDict(data)
        } else {
          that.$notify({
            title: "提示",
            message: res.msg,
            type: "error",
            duration: 2000
          });
        }
      })
    },
    afterGetDict(data) {
      if (data === 'qus_type') {
        let examRatioList = []
        for (var i = 0; i < this[data].length; i++) {
          examRatioList.push({
            qusPropType: this[data][i].key,
            qusPropTypeDesc: this[data][i].value,
            qusRadio: 10,
          })
        }
        this.form.papers = [{
          type: '',
          qusLibIds: [],
          examRatioList: examRatioList
        }]
      }
    },
  },
  created() {},
  mounted() {},
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {}
};
</script>
<style lang="scss" scoped>
.line {
  text-align: center;
}
.custom-exam-card {
  .el-card__body {
    padding: 20px 20px 0 20px !important;
  }
}
</style>
